define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goods/goods/index' + location.search,
                    add_url: 'goods/goods/add',
                    edit_url: 'goods/goods/edit',
                    del_url: 'goods/goods/del',
                    multi_url: 'goods/goods/multi',
                    import_url: 'goods/goods/import',
                    shelves_url: 'goods/goods/shelves',
                    dragsort_url: '',
                    table: 'goods',
                }
            });
            $('.btn-sjopera').hide();
            $('.goods_tab').on('click', function () {
                var status = $(this).data('value');
                $('.btn-sjopera').hide();
                if (status == 1) {
                    $('.btn-opera').hide();
                    $('.btn-sjopera').show();
                } else {
                    $('.btn-sjopera').hide();
                    $('.btn-opera').show();
                }
            });
            
            // $(".btn-delone").attr("title","删除");
            
            var table = $("#table");
            $('.btn-add').data("area", ["100%", "100%"]);
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-edit").data("area", ["100%", "100%"]);
            });
            // 指定第一个 tab 为激活状态，且获取对应、有效的数据列表
            table.on("post-common-search.bs.table", function (e, t) {
                // 这个代码块中的操作自行调整
                var link_obj = $("ul.nav-tabs li a[data-toggle='tab']").first();
                console.log(link_obj)
                link_obj.parent("li").addClass("active");
                $("select[name='status']", t.$commonsearch).val(link_obj.data("value"));
                $("li[role='menuitem']:has(input[data-field='status'])").hide();
                $('label[for="status"]').parent().css('display', 'none');
                $("#table").bootstrapTable('hideColumn', 'status');

            });


            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                fixedColumns: true,
                fixedRightNumber: 1,
                search: false,
                searchFormVisible: true,
                commonSearch: true,
                columns: [
                    [
                        {checkbox: true},
                        {
                            field: 'main_image',
                            title: __('Main_image'),
                            operate: false,
                            width: '100px',
                            formatter: function (value) {
                                html = '<div><img style="height:100px; width: 100px;" src=' + value + '></div>';
                                return html;
                            }
                        },
                        {
                            field: 'name',
                            title: __('Name'),
                            align: 'left',
                            operate: 'LIKE',
                            width: '400px',
                            formatter: function (value, row, index) {
                                if (row.attribute == 'new') {
                                    var attribute = '全新';
                                } else {
                                    var attribute = '二手';
                                }
                                var html = "<span>" + value + "</span> <br> " +
                                    "<br><span style=' font-size: 15px;'> ID: </span>" + row.goods_number + " " +
                                    "<br><span style=' font-size: 15px;'> 属性: </span>" + attribute;
                                return html;
                            },
                            cellStyle: {
                                css: {
                                    "max-width": "1400px",
                                    "white-space": "pre-line",
                                    "word-wrap": "break-word",
                                    "word-break": "break-all"
                                }
                            }
                        },
                        {field: 'goods_number', title: __('Goods_number'), operate: 'LIKE', visible: false},
                        {field: 'partnumber', title: __('Partnumber'), operate: 'LIKE', visible: false},


                        {field: 'en.name', title: __('en.name'), operate: 'LIKE', visible: false},
                        {
                            field: 'attribute',
                            title: __('Attribute'),
                            visible: false,
                            searchList: {"new": __('Attribute new'), "second": __('Attribute second')},
                            formatter: Table.api.formatter.normal
                        },
                        {field: 'ordinaryprice', title: __('Ordinaryprice'), width: '100px', operate: false},

                        {field: 'haveprice', title: __('Haveprice'), width: '100px', operate: false},
                        {field: 'agentprice', title: __('Agentprice'), width: '100px', operate: false},
                        {field: 'integral_num', title: __('Integral_num'), visible: false, operate: false},
                        {field: 'sales', title: __('Sales'), width: '100px', operate: false},
                        {field: 'virtual_sales_sum', title: __('Virtual_sales_sum'), visible: false, operate: false},
                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: {"1": __('Status 1'), "0": __('Status 0')},
                            operate: 'LIKE',
                            visible: false,
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'spec_type',
                            title: __('Spec_type'),
                            searchList: {"1": __('Spec_type 1'), "0": __('Spec_type 0')},
                            operate: false,
                            visible: false,
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'is_new',
                            title: __('Is_new'),
                            searchList: {"1": __('Is_new 1'), "0": __('Is_new 0')},
                            operate: false,
                            visible: false,
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'is_hot',
                            title: __('Is_hot'),
                            searchList: {"0": __('Is_hot 0'), "1": __('Is_hot 1')},
                            operate: false,
                            visible: false,
                            formatter: Table.api.formatter.normal
                        },
                        {
                            field: 'create_time',
                            title: __('Create_time'),
                            visible: false,
                            operate: false,
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate', title: __('Operate'), table: table,
                            width: '100px',
                            events: Table.api.events.operate,
                            cellStyle: function () {
                                return {
                                    css: {
                                        "max-width": "40px",
                                        "text-overflow": "ellipsis",
                                        "white-space": "initial",
                                    }
                                }
                            },
                            buttons: [
                                {
                                    name: 'edit',
                                    text: '编辑',
                                    classname: 'btn btn-xs btn-success btn-dialog',
                                    icon: 'fa fa-magic',
                                    extend: 'data-toggle="tooltip" data-area=\'["100%", "100%"]\'',
                                    url: $.fn.bootstrapTable.defaults.extend.edit_url,
                                    refresh: true,
                                },
                                {
                                    name: 'shelves',
                                    text: '上架',
                                    confirm: function (row) {
                                        return '确定上架';
                                    },
                                    classname: 'btn btn-xs btn-success btn-ajax',
                                    icon: 'fa fa-magic',
                                    url: 'goods/goods/shelves/status/0',
                                    refresh: true,
                                    visible: function (row) {
                                        if (row.status == 0) {
                                            return false;
                                        } else {
                                            return true;
                                        }
                                    }
                                },
                                {
                                    name: 'edit',
                                    text: '下架',
                                    classname: 'btn btn-xs btn-danger btn-ajax',
                                    icon: 'fa fa-magic',
                                    confirm: function (row) {
                                        return '确定下架';
                                    },
                                    url: 'goods/goods/shelves/status/1',
                                    refresh: true,
                                    visible: function (row) {
                                        if (row.status == 0) {
                                            return true;
                                        } else {
                                            return false;
                                        }
                                    }
                                },
                                {
                                    name: 'dapei',
                                    text: '搭售',
                                    classname: 'btn btn-xs btn-primary btn-dialog',
                                    icon: 'fa fa-list',
                                    extend: 'data-area=\'["100%", "100%"]\'',
                                    url: 'goods/collocation/index?ids',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },
                                {
                                    name: 'comments',
                                    text: '评论',
                                    classname: 'btn btn-xs btn-info btn-dialog',
                                    icon: 'fa fa-leaf',
                                    extend: 'data-area=\'["100%", "100%"]\'',
                                    url: 'goods/comment/index?type=goods',
                                    callback: function (data) {
                                        Layer.alert("接收到回传数据：" + JSON.stringify(data), {title: "回传数据"});
                                    },
                                    visible: function (row) {
                                        //返回true时按钮显示,返回false隐藏
                                        return true;
                                    }
                                },
                                {
                                    name: 'del',
                                    text: __('删除'),
                                    title: __('删除'),
                                    confirm: '您确定删除吗',
                                    classname: 'btn btn-xs btn-danger btn-magic btn-ajax',
                                    icon: 'fa fa-close',
                                    url: $.fn.bootstrapTable.defaults.extend.del_url,
                                    refresh: true,
                                    visible: true
                                },

                            ],
                            formatter: Table.api.formatter.operate,

                        }
                    ]
                ]
            });
            $(document).on("click", '.btn-opera', function () {
                var that = this;
                var ids = Table.api.selectedids(table);
                Layer.confirm(
                    __('确定下架操作吗?', ids.length),
                    {
                        icon: 3, title: __(''),
                        offset: 0,
                        shadeClose: true
                    },
                    function (index) {
                        Fast.api.ajax({
                            url: 'goods/goods/shelves',
                            type: "post",
                            data: {ids: ids, status: 1},
                        }, function () {
                        });

                        Layer.close(index);
                        table.bootstrapTable('refresh', {});

                    }
                )
            })
            $(document).on("click", '.btn-sjopera', function () {
                var that = this;
                var ids = Table.api.selectedids(table);
                Layer.confirm(
                    __('确定上架操作吗?', ids.length),
                    {
                        icon: 3, title: __(''),
                        offset: 0,
                        shadeClose: true
                    },
                    function (index) {
                        Fast.api.ajax({
                            url: 'goods/goods/shelves',
                            type: "post",
                            data: {ids: ids, status: 0},
                        }, function () {
                        });

                        Layer.close(index);
                        table.bootstrapTable('refresh', {});

                    }
                )
            })

            
            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            Controller.api.modelids();
            Controller.api.categorys();
            Controller.api.category();
            Controller.api.modelid();
            Controller.api.addcategory();
            // Form.api.bindevent($("form[role=form]"), function (_this, data, ret) {
            //     console.log(data)
            //     window.location.href = 'index';
            // });
        },
        shelves: function () {
            $(".btn-check").click(function () {
                console.log(2222)
            })
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
            Controller.api.modelids();
            Controller.api.categorys();
            Controller.api.category();
            Controller.api.modelid();
            Controller.api.addcategory();
        },
        del: function () {
            // console.log(2222)
            
            Controller.api.bindevent();
        },
        api: {
            addcategory: function () {
                $('.btn-categorynone').on('click', function () {
                    $('#c-category_status').val(1);
                    $('#categoryh').show();
                });
                $('.btn-categoryhidn').on('click', function () {
                    $('#c-category_status').val(0);
                    $('#categoryh').hide();
                });
            },
            categorys: function () {
                $('.category_select_box').on('click', '.category_select_item span', function () {
                    var ala = $(this).parent('.category_select_item').remove();
                    $(this).parent('.category_select_item').remove();
                    $('.category_to' + ala.data('id')).css('color', '#000009');
                    $('.category_tonext_to' + ala.data('id')).css('color', '#010105');
                    $('#checkca' + ala.data('id')).prop("checked", false);
                    updatecategoryIds();
                });

                function updatecategoryIds() {
                    var list = $('.category_select_item');
                    var ids = [];
                    for (var i = 0; i < list.length; i++) {
                        ids.push($(list[i]).data('id'));
                        $('.category_to' + $(list[i]).data('id')).css('color', '#f60707');
                        $('.category_tonext_to' + $(list[i]).data('id')).css('color', '#f60707');
                        $('#checkca' + $(list[i]).data('id')).prop("checked", true)

                    }
                    $("#c-category_id").val(ids.join(','));
                }


                $('.category_box').on('input', 'input.category_input', function () {

                    var category_item = $(this).parents('.category_item');
                    var key = $(this).val();
                    var pid = category_item.data('pid');
                    $.getJSON('goods/goods/getcategoryslist', {pid: pid, key: key}, function (data) {
                        var htmlstr = '';
                        for (var index in data) {
                            var item = data[index];
                            htmlstr += '<div class="category_li_item" data-id="' + item.id + '">\n' +
                                '<span class="category_toselect" style="width:1px;"><input type="checkbox" id="checkca' + item.id + '"></span>' +
                                ' <span class="category_tonext category_tonext_to' + item.id + '">' + item.name + '</span>\n' +
                                '</div>';
                        }
                        category_item.find('div.category_li_box').html(htmlstr);
                    });
                });

                // 选择数据
                $('.category_box').on('click', '.category_toselect', function () {
                    var ids = $("#c-category_id").val().split(',');
                    var id = $(this).parent('.category_li_item').data('id');

                    if (ids.indexOf(id + '') > -1) {
                        console.log(2)
                        $('#checkca' + id).prop("checked", false)
                        $('.category_to' + id).css('color', '#180303');
                        $('.category_tonext_to' + id).css('color', '#180303');
                        $(".category_select_item[data-id= " + id + " ]").remove();
                        updatecategoryIds();
                        return;
                    }
                    $('#checkca' + id).prop("checked", true)
                    $('.category_toselect category_to' + id).css('color', '#f10505');
                    $('.category_toselect category_tonext_to' + id).css('color', '#f60707');
                    var category_item = $(this).parents('.category_item');
                    var title = $(this).next('.category_tonext').text();
                    category_item.data('id', id);
                    category_item.data('title', title);
                    category_item.nextAll().remove();
                    var titles = title;
                    var list = category_item.prevAll();
                    for (var i = 0; i < list.length; i++) {
                        titles = $(list[i]).data('title') + '/' + titles;
                    }
                    var html = '<div class="category_select_item" data-id="' + id + '">' + titles + ' <span>删除</span></div>';
                    $('.category_select_box').append(html);
                    updatecategoryIds();
                });
                $('.category_box').on('click', '.category_tonext', function () {
                    if ($(this).data('child') == '0') {
                        return;
                    }
                    var category_item = $(this).parents('.category_item');
                    var id = $(this).parent('.category_li_item').data('id');
                    category_item.data('id', id);
                    category_item.data('title', $(this).text());
                    category_item.nextAll().remove();
                    $.getJSON('goods/goods/getcategoryslist', {pid: id}, function (data) {
                        var htmlstr = '<div class="category_item" data-pid="' + id + '" data-id="0" data-title="">\n' +
                            '<div class="category_input_box">\n' +
                            '<input type="text" class="category_input form-control">\n' +
                            '</div>\n' +
                            '<div class="category_li_box">\n';

                        for (var index in data) {
                            var item = data[index];
                            if (item.level == 2) {
                                if (item.child == 0) {
                                    htmlstr += '<div class="category_li_item" data-id="' + item.id + '">\n' +
                                        '<div class="category_toselect category_to' + item.id + '" style="width: 1px"><input type="checkbox" id="checkca' + item.id + '"></div> ' +
                                        '<div class="category_tonext category_tonext_to' + item.id + '" data-child="' + item.child +
                                        '">' + item.name + '</div><div class="category_next">';
                                } else {
                                    htmlstr += '<div class="category_li_item" data-id="' + item.id + '">\n' +
                                        '<div class="category_tonext" data-child="' + item.child +
                                        '">' + item.name + '</div><div class="category_next">';
                                }

                            } else {
                                htmlstr += '<div class="category_li_item" data-id="' + item.id + '">\n' +
                                    '<div class="category_toselect category_to' + item.id + '" style="width: 1px"><input type="checkbox" id="checkca' + item.id + '"></div> ' +
                                    '<div class="category_tonext category_tonext_to' + item.id + ' " data-child="' + item.child +
                                    '">' + item.name + '</div><div class="category_next">';
                            }

                            if (item.child > 0) {
                                htmlstr += '>';
                            }
                            htmlstr += '</div>\n' +
                                '</div>';
                        }
                        htmlstr += '</div>\n' +
                            '</div>';
                        category_item.parent('.category_box').append(htmlstr);
                        updatecategoryIds();
                    });
                });

            },
            modelids: function () {
                updateModelsIds();
                $('.models_select_box').on('click', '.models_select_item span', function () {
                    var ala = $(this).parent('.models_select_item').remove();
                    $(this).parent('.models_select_item').remove();
                    $('#check' + ala.data('id')).prop("checked", false);
                    updateModelsIds();
                });

                function updateModelsIds() {
                    var list = $('.models_select_item');
                    var ids = [];
                    for (var i = 0; i < list.length; i++) {
                        ids.push($(list[i]).data('id'));
                        $('#check' + $(list[i]).data('id')).prop("checked", true);
                    }
                    $("#c-models_id").val(ids.join(','));
                }

                $('.models_box').on('input', 'input.models_input', function () {
                    var models_item = $(this).parents('.models_item');
                    var key = $(this).val();
                    var pid = models_item.data('pid');
                    $.getJSON('goods/goods/getmodelslist', {pid: pid, key: key}, function (data) {
                        var htmlstr = '';
                        for (var index in data) {
                            var item = data[index];
                            htmlstr += '<div class="models_li_item" data-id="' + item.id + '">\n' +
                                '<span class="toselect" style="width: 1px;">' +
                                '<input type="checkbox" id="check' + item.id + '"> </span>' +
                                ' <span class="tonext tonextto' + item.id + '" >' + item.mergename + '</span>\n' +
                                '</div>';
                        }
                        models_item.find('div.models_li_box').html(htmlstr);
                    });
                });

                $('.models_box').on('click', '.tonextty ', function () {
                    let sum = $(this).parent().parent().parent().children('.models_li_item');
                    $.each(sum, function (i, item) {
                        var idt = item.getAttribute("data-id");
                        if ($(".models_select" + idt).length > 0) {
                            return;
                        }

                        var mename = $('.tonextto' + idt).text();
                        var html = '<div class="col-md-2 models_select_item models_select' + idt + '" data-id="' + idt + '">' + mename + ' <span>删除</span></div>';
                        $('.models_select_box').append(html);
                        updateModelsIds();
                    });
                });

                $('.models_box').on('click', '.cancel', function () {
                    var list = $('.models_select_item');
                    for (var i = 0; i < list.length; i++) {
                        $('#check' + $(list[i]).data('id')).prop("checked", false);
                    }
                    $('.models_select_box').html(" ");
                    $("#c-models_id").val('');
                });

                $('.models_box').on('click', '.toselect', function () {
                    var ids = $("#c-models_id").val().split(',');
                    var id = $(this).parent('.models_li_item').data('id');
                    if (ids.indexOf(id + '') > -1) {
                        $('#check' + id).prop("checked", false)
                        $(".models_select_item[data-id= " + id + " ]").remove();
                        updateModelsIds();
                        return;
                    }

                    $('#check' + id).prop("checked", true)
                    var models_item = $(this).parents('.models_item');
                    var title = $(this).next('.tonext').text();
                    models_item.data('id', id);
                    models_item.data('title', title);
                    models_item.nextAll().remove();
                    var titles = title;
                    var list = models_item.prevAll();
                    for (var i = 0; i < list.length; i++) {
                        titles = $(list[i]).data('title') + '/' + titles;
                    }
                    var html = '<div class="models_select_item" data-id="' + id + '">' + titles + ' <span>删除</span></div>';
                    $('.models_select_box').append(html);
                    updateModelsIds();
                });

                $('.models_box').on('click', '.tonext', function () {
                    if ($(this).data('child') == '0') {
                        return;
                    }
                    var models_item = $(this).parents('.models_item');
                    var id = $(this).parent('.models_li_item').data('id');
                    models_item.data('id', id);
                    models_item.data('title', $(this).text());
                    models_item.nextAll().remove();
                    $.getJSON('goods/goods/getmodelslist', {pid: id}, function (data) {
                        var htmlstr = '<div class="models_item" data-pid="' + id + '" data-id="0" data-title="">\n' +
                            '<div class="input_box">\n' +
                            '<input type="text" class="models_input form-control">\n' +
                            '</div>\n' +
                            '<div class="models_li_box">\n';
                        for (var index in data) {
                            var item = data[index];
                            htmlstr += '<div class="models_li_item" id="' + item.id + '" data-id="' + item.id + '">\n' +
                                '<div class="toselect toselect_to' + item.id + '" style="width: 1px"><input type="checkbox" id="check' + item.id + '"></div>' +
                                ' <div class="tonext tonextto' + item.id + '" style="font-size: 4px;" data-child="' + item.child +
                                '">' + item.mergename + '</div><div class="next">';
                            if (item.child > 0) {
                                htmlstr += '>';
                            }
                            htmlstr += '</div>\n' +
                                '</div>';
                        }
                        htmlstr += '</div>\n' +
                            '</div>';
                        models_item.parent('.models_box').append(htmlstr);
                        updateModelsIds();
                    });
                });
            },


            category: function () {
                $('.category_select_box1').on('click', '.category_select_item1 span', function () {
                    var ala = $(this).parent('.category_select_item1').remove();
                    $(this).parent('.category_select_item1').remove();
                    $('.category_to1' + ala.data('id')).css('color', '#000009');
                    $('.category_tonext1to' + ala.data('id')).css('color', '#01010e');
                    $('#checkcas' + ala.data('id')).prop('checked', false);
                    updatecategoryIds();
                });

                function updatecategoryIds() {
                    var list = $('.category_select_item1');
                    var ids = [];
                    for (var i = 0; i < list.length; i++) {
                        ids.push($(list[i]).data('id'));
                        $('.category_to1' + $(list[i]).data('id')).css('color', '#fc0808');
                        $('.category_tonext1to' + $(list[i]).data('id')).css('color', '#fc0808');
                        $('#checkcas' + $(list[i]).data('id')).prop('checked', true);
                    }
                    $("#c-category_id1").val(ids.join(','));

                }

                $('.category_box1').on('input', 'input.category_input1', function () {
                    var category_item = $(this).parents('.category_item1');
                    var key = $(this).val();
                    var pid = category_item.data('pid');
                    $.getJSON('goods/goods/getcategoryslist', {pid: pid, key: key}, function (data) {
                        var htmlstr = '';
                        for (var index in data) {
                            var item = data[index];

                            htmlstr += '<div class="category_li_item1" data-id="' + item.id + '">\n' +
                                '<span class="category_toselect1" style="width: 1px"><input type="checkbox" id="checkcas' + item.id + '"></span>' +
                                ' <span class="category_tonext1 category_tonext1to' + item.id + '" >' + item.name + '</span>\n' +
                                '</div>';
                        }
                        category_item.find('div.category_li_box1').html(htmlstr);
                    });
                });
                // 选择数据
                $('.category_box1').on('click', '.category_toselect1', function () {

                    var ids = $("#c-category_id1").val().split(',');
                    var id = $(this).parent('.category_li_item1').data('id');
                    if (ids.indexOf(id + '') > -1) {
                        console.log(id)
                        $('.category_to1' + id).css('color', '#000000');
                        $('.category_tonext1to' + id).css('color', '#000000');
                        $('#checkcas' + id).prop('checked', false);

                        $(".category_select_item1[data-id= " + id + " ]").remove();
                        updatecategoryIds();
                        return;
                    }
                    $('#checkcas' + id).prop('checked', true);
                    var category_item = $(this).parents('.category_item1');
                    var title = $(this).next('.category_tonext1').text();
                    category_item.data('id', id);
                    category_item.data('title', title);
                    category_item.nextAll().remove();
                    var titles = title;
                    var list = category_item.prevAll();
                    for (var i = 0; i < list.length; i++) {
                        titles = $(list[i]).data('title') + '/' + titles;
                    }
                    var html = '<div class="category_select_item1" data-id="' + id + '">' + titles + ' <span>删除</span></div>';
                    $('.category_select_box1').append(html);
                    updatecategoryIds();
                });
                $('.category_box1').on('click', '.category_tonext1', function () {

                    if ($(this).data('child') == '0') {
                        return;
                    }
                    var category_item = $(this).parents('.category_item1');
                    var id = $(this).parent('.category_li_item1').data('id');
                    category_item.data('id', id);
                    category_item.data('title', $(this).text());
                    category_item.nextAll().remove();
                    $.getJSON('goods/goods/getcategoryslist', {pid: id}, function (data) {
                        var htmlstr = '<div class="category_item1" data-pid="' + id + '" data-id="0" data-title="">\n' +
                            '<div class="category_input_box1">\n' +
                            '<input type="text" class="category_input1 form-control">\n' +
                            '</div>\n' +
                            '<div class="category_li_box1">\n';

                        for (var index in data) {
                            var item = data[index];
                            if (item.level == 2) {

                                if (item.child == 0) {
                                    htmlstr += '<div class="category_li_item1" data-id="' + item.id + '">\n' +
                                        '<div class="category_toselect1 category_to1' + item.id + '" style="width: 1px" ><input type="checkbox" id="checkcas' + item.id + '"></div> ' +
                                        '<div class="category_tonext1 category_tonext_to' + item.id + '" data-child="' + item.child +
                                        '">' + item.name + '</div><div class="category_next1">';
                                } else {
                                    htmlstr += '<div class="category_li_item1" data-id="' + item.id + '">\n' +
                                        '<div class="category_tonext1" data-child="' + item.child +
                                        '">' + item.name + '</div><div class="category_next1">';
                                }
                            } else {
                                htmlstr += '<div class="category_li_item1" data-id="' + item.id + '">\n' +
                                    '<div class="category_toselect1 category_to1' + item.id + '"  style="width: 1px" ><input type="checkbox" id="checkcas' + item.id + '"></div> ' +
                                    '<div class="category_tonext1 category_tonext1to' + item.id + ' " data-child="' + item.child +
                                    '">' + item.name + '</div><div class="category_next1">';
                            }

                            if (item.child > 0) {
                                htmlstr += '>';
                            }
                            htmlstr += '</div>\n' +
                                '</div>';
                        }
                        htmlstr += '</div>\n' +
                            '</div>';
                        category_item.parent('.category_box1').append(htmlstr);
                        updatecategoryIds();
                    });
                });

            },
            modelid: function () {
                updateModelsIds();
                $('.models_select_box1').on('click', '.models_select_item1 span', function () {
                    var ala = $(this).parent('.models_select_item1').remove();
                    $(this).parent('.models_select_item1').remove();
                    updateModelsIds();
                });

                function updateModelsIds() {
                    var list = $('.models_select_item1');
                    var ids = [];
                    for (var i = 0; i < list.length; i++) {
                        ids.push($(list[i]).data('id'));
                        $('#checke' + $(list[i]).data('id')).prop("checked", true);
                    }
                    $("#c-models_id1").val(ids.join(','));
                }

                $('.models_box1').on('input', 'input.models_input1', function () {
                    var models_item = $(this).parents('.models_item1');
                    var key = $(this).val();
                    var pid = models_item.data('pid');
                    $.getJSON('goods/goods/getmodelslist', {pid: pid, key: key}, function (data) {
                        var htmlstr = '';
                        for (var index in data) {
                            var item = data[index];
                            htmlstr += '<div class="models_li_item1" data-id="' + item.id + '">\n' +
                                '<span class="toselect1"><input type="checkbox" id="checke' + item.id + '"></span>' +
                                ' <span class="tonext1 tonextto1' + item.id + '">' + item.mergename + '</span>\n' +
                                '</div>';
                        }
                        models_item.find('div.models_li_box1').html(htmlstr);
                    });
                });

                $('.models_box1').on('click', '.cancels', function () {
                    var list = $('.models_li_item1');
                    for (var i = 0; i < list.length; i++) {
                        $('#checke' + $(list[i]).data('id')).prop("checked", false);
                    }
                    $('.models_select_box1').html(" ");
                    $("#c-models_id1").val('');
                });

                $('.models_box1').on('click', '.tonexttys', function () {
                    let sum = $(this).parent().parent().parent().children('.models_li_item1');
                    $.each(sum, function (i, item) {
                        var idt = item.getAttribute("data-id");
                        if ($(".models_select1" + idt).length > 0) {
                            return;
                        }
                        var mename = $('.tonextto1' + idt).text();
                        var html = '<div class="col-md-2 models_select_item1 models_select1' + idt + '" data-id="' + idt + '">' + mename + ' <span>删除</span></div>';
                        $('.models_select_box1').append(html);
                        updateModelsIds();
                    });
                });

                $('.models_box1').on('click', '.toselect1', function () {
                    var ids = $("#c-models_id1").val().split(',');
                    var id = $(this).parent('.models_li_item1').data('id');
                    if (ids.indexOf(id + '') > -1) {

                        $('#checke' + id).prop("checked", false)
                        $('.toselect_to1' + id).css('color', '#180303');
                        $('.tonextto1' + id).css('color', '#180303');
                        $(".models_select_item1[data-id= " + id + " ]").remove();
                        updateModelsIds();
                        return;
                    }

                    var models_item = $(this).parents('.models_item1');
                    var title = $(this).next('.tonext1').text();
                    models_item.data('id', id);
                    models_item.data('title', title);
                    models_item.nextAll().remove();
                    var titles = title;
                    var list = models_item.prevAll();
                    for (var i = 0; i < list.length; i++) {
                        titles = $(list[i]).data('title') + '/' + titles;
                    }
                    var html = '<div class="models_select_item1" data-id="' + id + '">' + titles + ' <span>删除</span></div>';
                    $('.models_select_box1').append(html);
                    updateModelsIds();
                });

                $('.models_box1').on('click', '.tonext1', function () {
                    if ($(this).data('child') == '0') {
                        return;
                    }
                    var models_item = $(this).parents('.models_item1');
                    var id = $(this).parent('.models_li_item1').data('id');
                    models_item.data('id', id);
                    models_item.data('title', $(this).text());
                    models_item.nextAll().remove();
                    $.getJSON('goods/goods/getmodelslist', {pid: id}, function (data) {
                        var htmlstr = '<div class="models_item1" data-pid="' + id + '" data-id="0" data-title="">\n' +
                            '<div class="input_box1">\n' +
                            '<input type="text" class="models_input1 form-control">\n' +
                            '</div>\n' +
                            '<div class="models_li_box1">\n';
                        for (var index in data) {
                            var item = data[index];
                            htmlstr += '<div class="models_li_item1" data-id="' + item.id + '">\n' +
                                '<div class="toselect1 toselect_to1' + item.id + '" style="width: 1px"><input type="checkbox" id="checke' + item.id + '"></div>' +
                                ' <div class="tonext1 tonextto1' + item.id + '" style="font-size: 4px;" data-child="' + item.child +
                                '">' + item.mergename + '</div><div class="next1">';
                            if (item.child > 0) {
                                htmlstr += '>';
                            }
                            htmlstr += '</div>\n' +
                                '</div>';
                        }
                        htmlstr += '</div>\n' +
                            '</div>';
                        models_item.parent('.models_box1').append(htmlstr);
                        updateModelsIds();
                    });
                });
            },
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
                setTimeout(function () {
                    Form.events.faupload($("form"));
                    Form.events.faselect($("form"));
                }, 1000);
                var iTime;
                var sku_json;
                var i = 0;
                $(document).on('change keyup changed', "#attr_json1.fieldlist input,#attr_json1.fieldlist textarea,#attr_json1.fieldlist select", function () {
                    clearTimeout(iTime);
                    iTime = setTimeout(function () {
                        remop();
                    }, 1000);
                });
                $(document).on('click', "span.btn-remove", function () {
                    console.log('121212');
                    remop();
                })
                $(document).on("fa.event.appendfieldlist", '.btn-append', function () {
                    //通用的表单组件事件绑定和组件渲染
                    Form.events.faupload($("form"));
                    Form.events.faselect($("form"));
                    Form.events.tagsinput($("form"));

                });
                remop = function () {
                    i++;
                    console.log('输入触发__', i);

                    var attr_json = JSON.parse($("#attr_json").val());
                    console.log('自动生成的', attr_json);
                    var attr = [];
                    attr_json.forEach(function (item) {
                        var temp = [];
                        var values = item.values.split(',');
                        values.forEach(function (val) {
                            temp.push(JSON.stringify({name: item.name, value: val}));
                        });
                        attr.push(temp);
                    });
                    var oldsku = $("#goods_sku").val() ? JSON.parse($("#goods_sku").val()) : [];


                    var sku = attrToSku(attr);
                    var skulist = [];

                    sku.forEach(function (item) {
                        var temp = skuSearch(item, oldsku);
                        temp.spec = "[" + item.join(',') + "]";
                        temp.spec_value_str = getSkuName(item);
                        skulist.push(temp)
                    });

                    console.log('生成好的', skulist);

                    $("#goods_sku").val(JSON.stringify(skulist));
                    $("#goods_sku").trigger("fa.event.refreshfieldlist");
                    Form.events.faupload($("form"));
                    Form.events.faselect($("form"));

                    // sku搜索
                    function skuSearch(spec, list) {
                        let r = {
                            price: 0,
                            haveprice: 0,
                            agentprice: 0,
                            stock: 0,
                            sales: 0,
                            image: '',
                        };
                        for (let i in list) {
                            let find = true;
                            // console.log(list[i].spec, 'item.spec');
                            for (let j in spec) {
                                // console.log(spec[j], 'name');
                                if (list[i].spec.indexOf(spec[j]) == -1) {
                                    find = false;
                                    break
                                }
                            }
                            if (find) {
                                r = list[i];
                                break;
                            }
                        }
                        return r;
                    }

                    // 获得sku的名称
                    function getSkuName(array) {
                        var names = array.reduce(function (total, current) {
                            return total.concat([JSON.parse(current).value]);
                        }, []);
                        return names.join(',');
                    }

                    // sku组合
                    function attrToSku(args) {
                        return args.reduce(
                            (total, current) => {
                                let ret = [];
                                total.forEach(a => {
                                    current.forEach(b => {
                                        ret.push(a.concat([b]));
                                    });
                                });
                                return ret;
                            },
                            [[]]
                        );
                    }
                }
                $(".btn-create").click(function () {
                    remop();
                });
            }
        }
    };
    return Controller;
});
